//
//  AppDelegate.m
//  LazyCat
//
//  Created by zhanshu on 15/9/7.
//  Copyright (c) 2015年 zhanshu. All rights reserved.
//

#import "AppDelegate.h"
#import "GuideView.h"
#import "BaseTabBarViewController.h"
//#import <BaiduMapAPI/BMapKit.h>//引入所有的头文件
#import "SelectNearProprieterController.h"
#import "LoginViewController.h"
#import "AFNetworkHandler.h"
#import "MyViewController.h"

#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>

//以下是腾讯QQ和QQ空间
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>

#import "WXApi.h"
#import "WeiboSDK.h"
#import <sys/utsname.h>
#import <ShareSDK/ShareSDK.h>
#import "OrderViewController.h"

#import "GeTuiSdk.h"
#import "MyViewController.h"
#import "WholesaleViewController.h"
// AppStore
//#define kAppId           @"0kIvlriyoa5DUkLZDVLW7"  
//#define kAppKey          @"DrRMHktxdyAZgdXGdUH487"
//#define kAppSecret       @"ipQUXZtZ2r5lY0e2s9chq3"

// 企业版
//#define kAppId           @"5gzwKVqYJS9PGymcKdNUx8"
//#define kAppKey          @"Z8al1TyV9U8idHUSMYnHF4"
//#define kAppSecret       @"ZPZwPiJfYyALhcN23NHDZ"

// 推送测试
//#define kAppId           @"yzIv0YGotB9aRHP7PPcg2"
//#define kAppKey          @"kyUQzudgfhADAtwEYqco56"
//#define kAppSecret       @"VwUPKPKwlW5aPl17Eofws6"


@interface AppDelegate ()<GeTuiSdkDelegate,UIAlertViewDelegate>// BMKLocationServiceDelegate
{
//    BMKMapManager* _mapManager;
//    BMKLocationService* _locService;
    NSInteger count;
    GuideView *guideView;
}
@property (strong, nonatomic) BaseTabBarViewController *tabVC;
@property (nonatomic) BOOL tap;

@property (nonatomic, assign) NSInteger alertCount; // 提示框弹出的次数
@property (nonatomic,copy)NSString *businessOrSalePlat;//是商家版(0)还是批发平台(1)..

@end

@implementation AppDelegate
- (void)initShare {
    /*
     懒猫社长(微信)
     AppID：wx274b4b066417cc12
     AppSecret：e7fa5fcab54c09608b3b6df111ac5cc6
     
     懒猫社长(新浪微博)
     App Key：26416955
     App Secret：2b97ce6168b6fac0d1cb9052901ad2bd
     
     
     懒猫社长(QQ)
     APP ID:1104856214
     APP KEY:lB1OHihDO8jJN6EA
     */
// =======================商家版=================================
    /*
     懒猫社长(微信)
     AppID：wxf47d1a9677116820
     AppSecret：8be5272612bf70f8f503cf7284c692ae
     
 wxf47d1a9677116820,tencent1105050097,QQ41DDB9F1,wb1273883023
     
     微博
     App Key：1273883023
     App Secret：53ecf8c10d02b911eb7972fc8dc73b08
     
     
     懒猫社长(QQ)
     APPID 1105050097
     APPKEY  nnMLtyalX2hucpXt
     */
    
    //原来的：53ecf8c10d02b911eb7972fc8dc73b08
    //网站上的：de43b49346eedba5227d4720d91793fe
    //[ShareSDK registerApp:@"e95a23fed3e8"];
    [ShareSDK registerApp:@"e95a7abbf9c2"];
    [ShareSDK connectSinaWeiboWithAppKey:@"1273883023"
                               appSecret:@"de43b49346eedba5227d4720d91793fe"
                             redirectUri:@"http://www.sharesdk.cn"
                             weiboSDKCls:[WeiboSDK class]];
    [ShareSDK connectQZoneWithAppKey:@"1105050097"
                           appSecret:@"nnMLtyalX2hucpXt"
                   qqApiInterfaceCls:[QQApiInterface class]
                     tencentOAuthCls:[TencentOAuth class]];
    [ShareSDK connectWeChatWithAppId:@"wxf47d1a9677116820"
                           appSecret:@"8be5272612bf70f8f503cf7284c692ae"
                           wechatCls:[WXApi class]];
    [ShareSDK connectQQWithQZoneAppKey:@"1105050097"
                     qqApiInterfaceCls:[QQApiInterface class]
                       tencentOAuthCls:[TencentOAuth class]];
    [ShareSDK connectCopy];
}
- (void)registerRemoteNotification {
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationSettings *uns = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound) categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:uns];
    }
    else {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
    }
    // [1]:使用APPID/APPKEY/APPSECRENT创建个推实例
    [self startSdkWith:kAppId appKey:kAppKey appSecret:kAppSecret];
    
    // [2]:注册APNS
//    [self registerRemoteNotification];
}

// 获取手机型号
- (NSString*)deviceVersion
{
    // 需要#import "sys/utsname.h"
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    //CLog(@"%@",deviceString);
    
    if ([deviceString isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
    if ([deviceString isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([deviceString isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([deviceString isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone3,2"])    return @"Verizon iPhone 4";
    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5S";
    if ([deviceString isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    if ([deviceString isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    if ([deviceString isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    if ([deviceString isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    if ([deviceString isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([deviceString isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    if ([deviceString isEqualToString:@"iPad2,2"])      return @"iPad 2 (GSM)";
    if ([deviceString isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    if ([deviceString isEqualToString:@"iPad3,4"])      return @"iPad 4 (WiFi)";
    if ([deviceString isEqualToString:@"i386"])         return @"Simulator";
    if ([deviceString isEqualToString:@"x86_64"])       return @"Simulator";
    
    //CLog(@"NOTE: Unknown device type: %@", deviceString);
    
    return deviceString;
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    [self initShare];
    
    count = 0;
    
    self.alertCount = 0;
    //vB3d3HhCgAn7oiOgXPPbdO3j   com.zhanshu.lazycat
    //AMvNvxUstmO9ecdzzyXGtxog   com.zhan.push1
    //lf2SVe6g0Xj0sh4OLdzMVM5l   com.zskj.lichuan
    // 百度地图
//    _mapManager = [[BMKMapManager alloc]init];
//    BOOL ret = [_mapManager start:@"lf2SVe6g0Xj0sh4OLdzMVM5l" generalDelegate:nil];
    
//    if (!ret) {
//        NSLog(@"manager start failed!");
//    }
    //取出店铺名称 店铺名称等相关信息 在选择之后保存在本地
//    [AppData share].proprieter = [ShopCommonModel getShopMess].name;
    
    BOOL doFirst = ![[NSUserDefualManager getValueByKey:@"DoFirstLogin"] boolValue];
    [AppData share].doFirst = doFirst;
    

/**************************************************/
//    if (doFirst) {
//        //第一次启动 引导图
//        [self theGuidedView];
//    }else {
//        _tabVC = [[BaseTabBarViewController alloc] init];
//        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:_tabVC];
//        nav.navigationBarHidden = YES;
//        self.window.rootViewController = nav;
//    }
//    [self.window makeKeyAndVisible];
//    // 第一次登陆
//    NSString *login = [NSUserDefualManager getValueByKey:@"doLogin"];
//    if ([login isEqualToString:@"1"]) {
//
//    }else{
//        LoginViewController *login = [[LoginViewController alloc] init];
//        [self.window.rootViewController presentViewController:login animated:NO completion:^{
//        }];
//    }
    WholesaleViewController *wholeSaleVC = [[WholesaleViewController alloc]init];
    NSString *isLanmao = [NSUserDefualManager getValueByKey:@"isLanmao"];
    _tabVC = [[BaseTabBarViewController alloc] init];
    UINavigationController *nav;
    if ([isLanmao isEqualToString:@"0"]) {//批发..
        nav = [[UINavigationController alloc] initWithRootViewController:wholeSaleVC];
    }else {//商家版..
        nav= [[UINavigationController alloc] initWithRootViewController:_tabVC];
    }
    nav.navigationBarHidden = YES;
    self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
    // 第一次登陆
    NSString *login = [NSUserDefualManager getValueByKey:@"doLogin"];
    
#warning *** -- 有第一次登陆或者反app登陆时无导航栏问题..
    if ([login isEqualToString:@"1"]) {
        self.window.rootViewController = nav;
    }else{
        LoginViewController *login = [[LoginViewController alloc] init];
        self.window.rootViewController = login;
    }
    
    
    //手机系统版本
    NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
    NSLog(@"手机系统版本: %@", phoneVersion);
    
    NSString *xh = [self deviceVersion];
    NSLog(@"手机型号：%@",xh);
    //设备名称
    NSString* deviceName = [[UIDevice currentDevice] systemName];
    NSLog(@"设 备名称: %@",deviceName );
    NSString *ipos = [deviceName stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    NSString *phone = [NSString stringWithFormat:@"%@%@,%@",ipos,phoneVersion,xh];
    
    NSString *stringStr = [phone stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"%@",stringStr);
    
    NSUserDefaults *iponeType = [NSUserDefaults standardUserDefaults];
    
    [iponeType setObject:stringStr forKey:@"iptype"];
    
    // 如果AppStore 版本值为:AppStore.IOS1.0.2
    // 如果企业版 版本值为:IOS1.0.2
    // 企业版越过1.0.3
    [iponeType setObject:banBen forKey:@"banben"];
 

/**************************************************/
    //定位
//    [self locationPart];
    //监听网络
    [self theNetWorkConnectStates];
    
    //通知
    [self registerRemoteNotification];
    
     self.tap = NO; // 点击通知
    
  NSDictionary* remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    
    NSLog(@"%@",remoteNotification);
    
    if (remoteNotification == NULL) {
        
        self.tap = NO; // 点击通知
        
    }else
    {
         self.tap = YES;
    }
    
    return YES;
}
- (void)theNetWorkConnectStates {
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"-------AFNetworkReachabilityStatusReachableViaWWAN------");
//                [[MessShowView share] showWithMess:@"当前网络--手机网络"];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"-------AFNetworkReachabilityStatusReachableViaWiFi------");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                [[MessShowView share] showWithMess:@"当前网络不可用"];
                break;
            default:
                break;
        }
    }];
}
- (void)theGuidedView {
    NSLog(@"the hei %f",ScreenHeight);
    NSArray *imgArr ;
    if (ScreenHeight == 480) {
        imgArr = @[@"引导页01 960.png",@"引导页02 960.png",@"引导页03 960.png"];
    }else if (ScreenHeight == 568) {
        imgArr = @[@"引导页01 1136.png",@"引导页02 1136.png",@"引导页03 1136.png"];
    }else if (ScreenHeight == 1334/2) {
        imgArr = @[@"引导页01 1334.png",@"引导页02 1334.png",@"引导页03 1334.png"];
    }else if (ScreenHeight == 2208/3) {
        imgArr = @[@"引导页01 2208.png",@"引导页02 2208.png",@"引导页03 2208.png"];
    }
    
   guideView = [[GuideView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    [guideView theGuideImg:imgArr];
    [guideView.endbtn addTarget:self action:@selector(endAction) forControlEvents:UIControlEventTouchUpInside];
    [self.window addSubview:guideView];
}
- (void)endAction {

    for (UIView *view in guideView.subviews) {
        [view removeFromSuperview];
    }
    [guideView removeFromSuperview],guideView = nil;
    SelectNearProprieterController *selectProprieter = [[SelectNearProprieterController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:selectProprieter];
    nav.navigationBarHidden = YES;
    self.window.rootViewController = nav;
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    // [EXT] APP进入后台时，通知个推SDK进入后台
    [GeTuiSdk enterBackground];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
 
    // [EXT] 重新上线
    [self startSdkWith:kAppId appKey:kAppKey appSecret:kAppSecret];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
-(void) stopSdk {
    [GeTuiSdk enterBackground];
}
//#pragma mark- 定位
//- (void)reLocation {
//    count = 0;
//    _locService = nil;
//    [self locationPart];
//}
//- (void)locationPart {
//    //定位
//    _locService = [[BMKLocationService alloc]init];
//    _locService.delegate = self;
//    [_locService startUserLocationService];
//}
//- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
//{
//    //定位成功
//
//    [AppData share].lat = userLocation.location.coordinate.latitude;
//    [AppData share].lng = userLocation.location.coordinate.longitude;
//    
//    if (count == 0) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:LC_Location_result object:[NSNumber numberWithBool:YES]];
//        count = 1;
//    }
//    
//}
//- (void)didFailToLocateUserWithError:(NSError *)error {
//    //定位失败
//    if (count == 0) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:LC_Location_result object:[NSNumber numberWithBool:NO]];
//        count = 0;
//    }
//    
////    [AppData share].lat = 31.143887;
////    [AppData share].lng = 121.32719;
//}
#pragma mark - 推送部分
#pragma mark - background fetch  唤醒
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    //[5] Background Fetch 恢复SDK 运行
    [GeTuiSdk resume];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    _deviceToken = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"deviceToken:%@", _deviceToken);
    
    // [3]:向个推服务器注册deviceToken
    [GeTuiSdk registerDeviceToken:_deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    // [3-EXT]:如果APNS注册失败，通知个推服务器
    [GeTuiSdk registerDeviceToken:@""];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userinfo {
    // [4-EXT]:处理APN
    NSString *payloadMsg = [userinfo objectForKey:@"payload"];
    if (payloadMsg) {
        NSString *record = [NSString stringWithFormat:@"[APN]%@, %@", [NSDate date], payloadMsg];
    }
}
#pragma mark - 点击通知栏走
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    // [4-EXT]:处理APN
    self.tap = YES;
    NSString *payloadMsg = [userInfo objectForKey:@"payload"];
    
    NSDictionary *aps = [userInfo objectForKey:@"aps"];
    NSNumber *contentAvailable = aps == nil ? nil : [aps objectForKeyedSubscript:@"content-available"];
    
    if (payloadMsg && contentAvailable) {
        NSString *record = [NSString stringWithFormat:@"[APN]%@, %@, [content-available: %@]", [NSDate date], payloadMsg, contentAvailable];
    }
    completionHandler(UIBackgroundFetchResultNewData);
    
    
}

- (void)startSdkWith:(NSString *)appID appKey:(NSString *)appKey appSecret:(NSString *)appSecret
{
    
    NSError *err = nil;
    
    //[1-1]:通过 AppId、 appKey 、appSecret 启动SDK
    [GeTuiSdk startSdkWithAppId:appID appKey:appKey appSecret:appSecret delegate:self error:&err];
    
    //[1-2]:设置是否后台运行开关
    [GeTuiSdk runBackgroundEnable:YES];
    
    // 手机唯一标示符
      NSString *cid =  [GeTuiSdk clientId];
    NSLog(@"%@",cid);
    NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults];
    
    [userDefaul setObject:cid forKey:@"cid"];
    
}

- (void)setDeviceToken:(NSString *)aToken
{
    
    [GeTuiSdk registerDeviceToken:aToken];
}

- (BOOL)setTags:(NSArray *)aTags error:(NSError **)error
{
    return [GeTuiSdk setTags:aTags];
}

- (NSString *)sendMessage:(NSData *)body error:(NSError **)error {
    
    return [GeTuiSdk sendMessage:body error:error];
}

- (void)bindAlias:(NSString *)aAlias {
    [GeTuiSdk bindAlias:aAlias];
}

- (void)unbindAlias:(NSString *)aAlias {
    
    [GeTuiSdk unbindAlias:aAlias];
}
- (void)testGetClientId {
    NSString *clientId = [GeTuiSdk clientId];
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"当前的CID" message:clientId delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];
}

#pragma mark - GexinSdkDelegate
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId
{
    // [4-EXT-1]: 个推SDK已注册，返回clientId
    if (_deviceToken) {
        [GeTuiSdk registerDeviceToken:_deviceToken];
    }
}
#pragma mark - 收到后台推送
- (void)GeTuiSdkDidReceivePayload:(NSString *)payloadId andTaskId:(NSString *)taskId andMessageId:(NSString *)aMsgId fromApplication:(NSString *)appId
{
    
    // [4]: 收到个推消息
    NSData* payload = [GeTuiSdk retrivePayloadById:payloadId];
    NSString *payloadMsg = nil;
    if (payload) {
        payloadMsg = [[NSString alloc] initWithBytes:payload.bytes
                                              length:payload.length
                                            encoding:NSUTF8StringEncoding];
        NSLog(@"推送信息：%@",payloadMsg);
    }
    NSError *err;
    NSDictionary *messDic ;
    if (payload) {
         messDic = [NSJSONSerialization JSONObjectWithData:payload
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
    }
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return;
    }
    
//============================================================================================
//                                  通知
//============================================================================================
    
    NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:@"1",@"textOne",@"2",@"textTwo", nil];
    //创建通知
    NSNotification *noti =[NSNotification notificationWithName:@"tongzhi" object:nil userInfo:dict];
    //通过通知中心发送通知
    [[NSNotificationCenter defaultCenter] postNotification:noti];
 
    
//============================================================================================

    /********************************/
     if (self.tap == NO) {
    //定义变量，表示音频文件
    SystemSoundID soundID;
    //加载音频文件
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[[NSBundle mainBundle]URLForResource:@"xiaoxi" withExtension:@"mp3"], &soundID);
 
    NSString *lingsheng = [NSUserDefualManager getValueByKey:@"lingsheng"];
    NSString *zhendong = [NSUserDefualManager getValueByKey:@"zhendong"];
    NSLog(@"%@=====%@",lingsheng,zhendong);
    
    if ([lingsheng isEqualToString:@"1"] && [zhendong isEqualToString:@"1"]) {//铃声加震动
        
        AudioServicesPlaySystemSound(soundID);
       
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }else if ([lingsheng isEqualToString:@"0"] && [zhendong isEqualToString:@"1"]) {//震动
        
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }else if ([lingsheng isEqualToString:@"1"] && [zhendong isEqualToString:@"0"]) {//铃声
        
         AudioServicesPlaySystemSound(soundID);
    }else {//静音
        
        
    }
     }
//
    /********************************/
    if (messDic) {
        if ([messDic isKindOfClass:[NSDictionary class]]) { // 通知退出
            NSString *type = [messDic[@"type"] safeString];
            if ([type isEqualToString:@"ChangeMobilephoneToSeller"]){
                
                if (self.alertCount == 0) {
                    self.alertCount ++;
                    UIAlertView *aler = [[UIAlertView alloc] initWithTitle:nil message:@"您的账号已在另一台设备上登录,是否重新登录" delegate:self cancelButtonTitle:@"登录" otherButtonTitles:@"退出", nil];
                    [aler show];
                }
                
            }else{
                if (self.tap == NO) {
                    //定义变量，表示音频文件
                    SystemSoundID soundID;
                    //加载音频文件
                    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[[NSBundle mainBundle]URLForResource:@"xiaoxi" withExtension:@"mp3"], &soundID);
                    
                    NSString *lingsheng = [NSUserDefualManager getValueByKey:@"lingsheng"];
                    NSString *zhendong = [NSUserDefualManager getValueByKey:@"zhendong"];
                    NSLog(@"%@=====%@",lingsheng,zhendong);
                    
                    if ([lingsheng isEqualToString:@"1"] && [zhendong isEqualToString:@"1"]) {//铃声加震动
                        
                        AudioServicesPlaySystemSound(soundID);
                        
                        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
                    }else if ([lingsheng isEqualToString:@"0"] && [zhendong isEqualToString:@"1"]) {//震动
                        
                        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
                    }else if ([lingsheng isEqualToString:@"1"] && [zhendong isEqualToString:@"0"]) {//铃声
                        
                        AudioServicesPlaySystemSound(soundID);
                    }else {//静音
                        
                        
                    }
                }

            }
        }
    }
    /********************************/
    
    if (self.tap == YES) {
    
    
    if (messDic) {
        if ([messDic isKindOfClass:[NSDictionary class]]) {
            NSString *title = [messDic[@"title"] safeString];
            NSString *type = [messDic[@"type"] safeString];
            BOOL doDetail = NO;
//            订单支付成功或货到付款推送给商家
            if ([type isEqualToString:@"OrderPaySuccessOrPayReceiveToSeller"]) {

                
            OrderViewController *order = [[OrderViewController alloc] init];
                order.todayOrder = 3;
                order.tuisong = @"y"; // 返回
                [[self getCurrentVC] presentViewController:order animated:YES completion:^{
                    self.tap = NO;
                }];
                doDetail = NO;
                self.tap = NO;
            }else if ([type isEqualToString:@"ApplyReturnProductToSeller"]) { // 申请退货推送给商家
                
                OrderViewController *order = [[OrderViewController alloc] init];
                order.tuisong = @"y"; // 返回
                order.tuiHuoManager = YES;
                [[self getCurrentVC] presentViewController:order animated:YES completion:^{
                    self.tap = NO;
                }];
                doDetail = YES;
                self.tap = NO;
            }else if ([type isEqualToString:@"ChangeMobilephoneToSeller"]) { // 通知退出
                doDetail = NO;
                self.tap = NO;
            }else if ([type isEqualToString:@"lanmao_url"]) {
                doDetail = NO;
                self.tap = NO;
            }else if ([type isEqualToString:@"CustomerRemindSupplierPost"]){// 客户催促商家发货
                doDetail = NO;
                self.tap = NO;
            }else if ([type isEqualToString:@"ServerCustomerRemindSupplierPost"]){// 云端提醒商家发货
                // 调到代发货
                OrderViewController *order = [[OrderViewController alloc] init];
                order.todayOrder = 0;
                order.tuisong = @"y"; // 返回
                [[self getCurrentVC] presentViewController:order animated:YES completion:^{
                    self.tap = NO;
                }];
                doDetail = NO;
                self.tap = NO;
            }
        }
    }
    }   //self.tap == YES
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
          NSLog(@"确定");
        self.alertCount =0;
        MyViewController *myview = [[MyViewController alloc] init];
        [myview loginFirst];
        
    }else{
        NSLog(@"取消");
        self.alertCount =0;
        LoginViewController *loginVC = [[LoginViewController alloc]init];
        self.window.rootViewController = loginVC;
 
        
        NSString *cid = [ NSUserDefualManager getValueByKey:@"cid"];
        NSString *url = [NSString stringWithFormat:businessLoginOut,cid,[AppData share].username];
        [AFNetworkHandler GETWithAFNByURL:url completion:^(id result) {
            NSDictionary *dict = result;
            NSString *r = dict[@"r"];
            if ([r isEqualToString:@"T"]) {
                [[AppData share] clearValue];
                [NSUserDefualManager storageValue:@"" forKey:UserName];
                [NSUserDefualManager storageValue:@"" forKey:Psw];
                [AppData share].baseTabVC.redLable.hidden = YES;
                [NSUserDefualManager storageValue:@"0" forKey:@"doLogin"];
                NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults]; // 蓝牙开关状态
                [userDefaul setObject:@"off" forKey:@"switch"];
            }
        }];
    }
}


- (UIViewController *)getCurrentVC
{
    UIViewController* activityViewController = nil;
    
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    if(window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow *tmpWin in windows)
        {
            if(tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    NSArray *viewsArray = [window subviews];
    if([viewsArray count] > 0)
    {
        UIView *frontView = [viewsArray objectAtIndex:0];
        
        id nextResponder = [frontView nextResponder];
        
        if([nextResponder isKindOfClass:[UIViewController class]])
        {
            activityViewController = nextResponder;
        }
        else
        {
            activityViewController = window.rootViewController;
        }
    }
    
    return activityViewController;
}

@end
